//
//  UserCount.swift
//  XCMicroBo
//
//  Created by 1 on 16/3/9.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

let userInfoKey = "cn.xuechao.www"



class UserCount: NSObject {

    static let shareAcount = UserCount()
    //access_token 访问用户数据的依据
    var access_token:String?
    
    //用户的昵称
    var name:String?
    
    //用户的uid
    var uid:String?
    
    //用户的头像
    var avatar_large : String?
    
    //access_token的生命周期，单位是秒数。  当前用户token 过多少秒之后会过期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //计算过期日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //定义一个Bool属性  用来确定用户是否登录
    var userLoginFlage : Bool {
        
        return access_token != nil
    }
    
    
    
    //token过期日期
    //2021-03-07 08:37:27 +0000 开发者账号的过期日期 是5年
    //普通用户的账户的过期日期是  3天
    var expires_date: NSDate?
    
    //过滤掉kvc赋值时没有定义的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    
    //单例模式
    override private init() {
        
        super.init()
        
        self.loadData()
        
    }
    
    
    override var description: String {
        //只读属性

        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date","avatar_large"]
        
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        return accountDict.description
    }

}


extension UserCount{
    
    //保存数据的方法
    func saveData(dict:[String:NSObject]){
        
        setValuesForKeysWithDictionary(dict)
        
        //字典中不能保存空数据
        //以字典的形式  将用户的数据保存到沙盒中
        let defaults = NSUserDefaults.standardUserDefaults()
        
        //要转化成字典的key
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let userInfoDict = self.dictionaryWithValuesForKeys(keys)
        
        defaults.setObject(userInfoDict, forKey: userInfoKey)
        
        //同步
        defaults.synchronize()
        
        print("\(__FUNCTION__)\(self)")
    }
    
    
    //加载数据的方法
    func loadData(){
        
        //从沙盒中  读出保存的字典
        let defaults = NSUserDefaults.standardUserDefaults()
        
        let dict = defaults.objectForKey(userInfoKey)
        
        guard let loadUserInfoDict = dict as? [String : NSObject] else{
            
            return
        }
        
        //将取出的数据转换成模型
        setValuesForKeysWithDictionary(loadUserInfoDict)
        
        print("\(__FUNCTION__)\(self)")
        
        //用过期日期 和当前的日期进行比较
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //过期日期大于 当前日期
            print("token 正常")
            
            
        } else {
            print("用户token 已过期")
            self.access_token = nil
        }

    }

}

extension UserCount{
    
    
    func loadAccessToken(code:String , finished:(isSuccess:Bool)->()){
        
        
        //获取管理工具
        let manager = AFHTTPSessionManager()
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //插入类型解析器
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //拼接参数
        let prameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        //发送post请求
        manager.POST(urlString, parameters: prameters, progress: nil, success: { (_, result) -> Void in
            
            guard let dict = result as? [String:NSObject] else {
                
                SVProgressHUD.showErrorWithStatus("数据格式错误")
                
                return
            }
            
            //           let token = dict["access_token"]
            
            //            print(token)
            
            
            self.loadUserInfo(dict, finished: finished)
            
            
            }) { (_, error) -> Void in
                
                print(error)
        }

        
        print("\(__FUNCTION__)\(self)")
        
    }
    
    //加载数据
    func loadUserInfo(dict:[String:NSObject],finished:(isSuccess:Bool)->()){
        
    //获取token
        let token = dict["access_token"] as! String
        
        print(token)
        //获取uid
        let uid = dict["uid"] as! String
        
        let urlString =  "https://api.weibo.com/2/users/show.json"
        
        //拼接参数
        let parameters:[String:String] = ["access_token" : token, "uid" : uid]

        
        let manager = AFHTTPSessionManager()
        
        manager.GET(urlString, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            
//            let dict = response as? [String : NSObject]
            
            guard var diction = response as? [String : NSObject] else {
                
                
                finished(isSuccess: false)
                return
            }
            
            //合并字典
            for (key,value)in dict {
                
                diction[key] = value
            }
            
            //在闭包中调用方法  需要用self修饰
            
            self.saveData(diction)
            
            finished(isSuccess: true)
            
            }) { (_, error) -> Void in
         
                finished(isSuccess: false)
                
                print(error)
        }
        
         print("\(__FUNCTION__)\(self)")
    
    }
    
    

   
}
